<template>
  <div class="diary">
    <div class="diary-content">
      <div class="calendar-header">
        <a-button type="primary" @click="showTimeline" class="timeline-toggle-btn">
          <HistoryOutlined /> 日记记录
        </a-button>
      </div>
      <a-calendar mode="month" :locale="locale" style="width: 100%" v-model:value="value" @select="activeDate">
        <template #dateFullCellRender="{ current }">
          <div :class="[
            'dateCellRender',
            current.format('YYYY-MM-DD') == value?.format('YYYY-MM-DD')
              ? 'activeDate'
              : '',
            getDateContext(current) ? 'hasTask' : '',
          ]">
            <div :class="['date-content', getDateContext(current) ? 'hasTask' : '']">
              {{ current.date() }}
            </div>

            <span title="编辑" @click.stop="selectDate(current)" class="iconfont icon-editor"></span>
          </div>
        </template>
      </a-calendar>
    </div>

    <a-drawer title="日记记录" placement="right" :open="timelineVisible" :maskClosable="false" :closable="false"
      width="50%">
      <template #extra>
        <a-button type="text" @click="closeTimeline" class="custom-close-btn">
          <CloseOutlined />
        </a-button>
      </template>
      <!-- 实现输入关键字，根据日历 content 内容 模糊匹配，帅选出所有日历 -->

      <div class="timeline-drawer">
        <!-- 添加搜索框 -->
        <div class="timeline-search">
          <a-input-search v-model:value="searchKeyword" allowClear placeholder="输入关键字搜索日记内容" style="margin-bottom: 16px"
            @search="onSearch" />
        </div>

        <div v-if="Object.keys(filteredGroupedDiaries).length > 0">
          <div v-for="(diaries, yearMonth) in filteredGroupedDiaries" :key="yearMonth" class="timeline-group">
            <div class="timeline-group-header">
              <div class="timeline-group-title">{{ yearMonth }}</div>
              <div class="timeline-group-actions">
                <a-popconfirm :title="'确定要删除' + yearMonth + '的所有日记吗?'" @confirm="deleteMonthDiaries(diaries, yearMonth)"
                  @cancel="cancelDelete" ok-text="确定" cancel-text="取消">
                  <a-button type="text" size="small" class="batch-delete-btn">
                    <DeleteOutlined />
                  </a-button>
                </a-popconfirm>
              </div>
            </div>
            <a-timeline>
              <a-timeline-item v-for="(item, index) in diaries" :key="index">
                <div class="timeline-item">
                  <div class="timeline-main" @click="openDiaryFromTimeline(item.date)">
                    <div class="timeline-date">{{ dayjs(item.date).format('MM-DD') }}</div>
                    <div class="timeline-content" v-html="getPreviewContent(item.content)"></div>
                  </div>
                  <div class="timeline-actions">
                    <a-popconfirm title="确定要删除这篇日记吗?" @confirm="deleteDiary(item)" @cancel="cancelDelete" ok-text="确定"
                      cancel-text="取消">
                      <a-button type="text" size="small" class="delete-btn">
                        <DeleteOutlined />
                      </a-button>
                    </a-popconfirm>
                  </div>
                </div>
              </a-timeline-item>
            </a-timeline>
          </div>
        </div>
        <a-empty v-else description="暂无匹配的日记记录" />
      </div>
    </a-drawer>

    <a-modal v-model:open="open" :title="dayjs(value).format('YYYY-MM-DD')" style="width: 80%;" :maskClosable="false"
      :destroyOnClose="true" :footer="false">
      <div class="task-content">
        <MyEditor v-if="isEdit" ref="MyEditorRef" style="height: calc(100% - 25px)" :content="currenContent" />
        <div v-else class="editor-content-view" v-highlight style="
            height: calc(100%);
            font-size: 14px;
            padding: 10px;
            line-height: 22px;
            overflow-y: scroll;
            width: 100%;
            white-space: pre-wrap;
            word-break: break-all;
          ">
          <div v-html="currenContent"></div>
        </div>
      </div>
      <div class="task-footer">
        <a-button @click="open = false">取消</a-button>
        <a-button v-if="!isEdit" type="primary" @click="isEdit = !isEdit">编辑</a-button>
        <a-button v-else type="primary" @click="handleOk">保存</a-button>
      </div>
    </a-modal>

  </div>
</template>

<script setup lang="ts">
import { inject, onMounted, ref, watch, computed, onActivated } from "vue";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";
import dayjs, { Dayjs } from "dayjs";
import { generateUUID } from "../../utils/helper";
import { message } from "ant-design-vue";
import MyEditor from "../../components/MyEditor.vue";
import { DeleteOutlined, HistoryOutlined, CloseOutlined } from "@ant-design/icons-vue";
import "./custom-wangeditor.css"; // 引入 css

const MyEditorRef = ref<any>(null);

const isEdit = ref<boolean>(false);
const value = ref<Dayjs>(dayjs());
const currenContent = ref<any>("");
const listData = ref<any>([]);

// 时间轴抽屉可见性
const timelineVisible = ref<boolean>(false);

// 搜索关键字
const searchKeyword = ref<string>('');

// 计算属性：按年月分组的日记列表
const groupedDiaries = computed(() => {
  // 先按日期排序
  const sorted = [...listData.value].sort((a, b) => {
    return new Date(b.date).getTime() - new Date(a.date).getTime();
  });

  // 按年月分组
  const grouped: Record<string, any[]> = {};
  sorted.forEach(item => {
    const yearMonth = dayjs(item.date).format('YYYY年MM月');
    if (!grouped[yearMonth]) {
      grouped[yearMonth] = [];
    }
    grouped[yearMonth].push(item);
  });

  return grouped;
});

// 计算属性：根据搜索关键字筛选后的分组日记列表
const filteredGroupedDiaries = computed(() => {
  // 如果没有搜索关键字，则返回所有日记
  if (!searchKeyword.value.trim()) {
    return groupedDiaries.value;
  }

  // 根据关键字筛选日记内容
  const filtered: Record<string, any[]> = {};
  Object.keys(groupedDiaries.value).forEach(yearMonth => {
    const filteredDiaries = groupedDiaries.value[yearMonth].filter(item => {
      // 移除HTML标签后进行模糊匹配
      const contentText = item.content.replace(/<[^>]+>/g, '').toLowerCase();
      const keyword = searchKeyword.value.toLowerCase();
      return contentText.includes(keyword);
    });

    if (filteredDiaries.length > 0) {
      filtered[yearMonth] = filteredDiaries;
    }
  });

  return filtered;
});

const getList = async () => {
  try {
    // 通过Express API获取日记数据
    const response = await fetch('http://localhost:32068/api/diarys');
    const result = await response.json();
    console.log('Diarys API Response:', result);
    
    // 使用API返回的数据
    if (result.data && Array.isArray(result.data)) {
      listData.value = result.data;
    } else {
      listData.value = [];
    }
  } catch (error) {
    console.error("通过API获取日记数据失败:", error);
    // 如果API请求失败，将列表设为空数组
    listData.value = [];
  }
};

onMounted(async () => {
  await getList();
});

onActivated(async()=>{
  await getList();
})

const getDateContext = (value: Dayjs) => {
  const date = dayjs(value).format("YYYY-MM-DD");
  const item = listData.value.find(
    (item: { date: string }) => item.date === date
  );
  return item ? item.content : "";
};

const getContent = (date: string) => {
  return listData.value.find((item: { date: string }) => item.date === date)
    ?.content;
};

const getCurrentData = (date: string) => {
  return listData.value.find((item: { date: string }) => item.date === date);
};

// 显示时间轴抽屉
const showTimeline = () => {
  timelineVisible.value = true;
};

// 从时间轴打开日记
const openDiaryFromTimeline = (date: string) => {
  // timelineVisible.value = false;
  value.value = dayjs(date);
  selectDate(dayjs(date));
};

// 获取内容预览（移除HTML标签）
const getPreviewContent = (content: string) => {
  if (!content) return '';
  const text = content.replace(/<[^>]+>/g, '');
  return text.length > 30 ? text.substring(0, 30) + '...' : text;
};

const selectDate = (date: Dayjs) => {
  console.log(date.format("YYYY-MM-DD"));
  currenContent.value = getContent(date.format("YYYY-MM-DD"));
  currenContent.value ? (isEdit.value = false) : (isEdit.value = true);
  showModal();
};

const activeDate = (date: Dayjs) => {
  console.log(date.format("YYYY-MM-DD"));
};

const open = ref<boolean>(false);

const showModal = () => {
  open.value = true;
};

const bindClickImageShow = inject<any>("bindClickImageShow")

watch(
  () => open.value,
  (val) => {
    if (!val) {
      currenContent.value = "";
      isEdit.value = false;
      getList();
    } else {
      bindClickImageShow()
    }
  }
);

const handleOk = async (e: MouseEvent) => {
  let currentData = getCurrentData(dayjs(value.value).format("YYYY-MM-DD"));
  const content = MyEditorRef?.value?.getContext()
  if (!content) {
    message.error("请输入内容");
    return;
  }
  currenContent.value = content;
  try {
    if (!currentData) {
      const dateNote = {
        id: generateUUID(),
        date: dayjs(value.value).format("YYYY-MM-DD"),
        content: currenContent.value,
      };
      
      // 通过API创建新的日记
      const response = await fetch('http://localhost:32068/api/diarys', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(dateNote),
      });
      
      const result = await response.json();
      if (result.code === 201) {
        message.success("保存成功");
      } else {
        message.error("保存失败");
      }
    } else {
      // 通过API更新现有日记
      const response = await fetch(`http://localhost:32068/api/diarys/${currentData.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content: currenContent.value,
        }),
      });
      
      const result = await response.json();
      if (result.code === 200) {
        message.success("保存成功");
      } else {
        message.error("保存失败");
      }
    }
    isEdit.value = false;
    bindClickImageShow();
    getList(); // 重新获取列表数据
  } catch (error) { 
    console.error("保存日记失败:", error);
    message.error("保存失败");
  }
  // open.value = false;
};

// 删除单篇日记
const deleteDiary = async (item: any) => {
  try {
    // 通过API删除日记
    const response = await fetch(`http://localhost:32068/api/diarys/${item.id}`, {
      method: 'DELETE',
    });
    
    const result = await response.json();
    if (result.code === 200) {
      message.success("删除成功");
      getList(); // 重新获取列表数据
    } else {
      message.error("删除失败");
    }
  } catch (error) {
    message.error("删除失败");
    console.error("删除日记失败:", error);
  }
};

// 批量删除某个月的所有日记
const deleteMonthDiaries = async (diaries: any[], yearMonth: string) => {
  try {
    // 批量删除该月份的所有日记
    let successCount = 0;
    for (const diary of diaries) {
      try {
        const response = await fetch(`http://localhost:32068/api/diarys/${diary.id}`, {
          method: 'DELETE',
        });
        
        const result = await response.json();
        if (result.code === 200) {
          successCount++;
        }
      } catch (error) {
        console.error("删除日记失败:", error);
      }
    }
    
    if (successCount === diaries.length) {
      message.success(`成功删除${yearMonth}的所有日记`);
    } else if (successCount > 0) {
      message.success(`部分删除成功，${successCount}/${diaries.length}篇日记已删除`);
    } else {
      message.error("删除失败");
    }
    
    getList(); // 重新获取列表数据
  } catch (error) {
    message.error("批量删除失败");
    console.error("批量删除日记失败:", error);
  }
};

const cancelDelete = () => {
  // 取消删除操作
  console.log("取消删除");
};

const closeTimeline = () => {
  // 关闭时间轴
  timelineVisible.value = false;
  // 清空搜索关键字
  searchKeyword.value = '';
};

// 搜索处理函数
const onSearch = (value: string) => {
  searchKeyword.value = value;
};
</script>

<style scoped>
.diary {
  padding: 12px 55px;
  height: calc(100% - 20px);
  overflow-y: hidden;
}

.diary-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.calendar-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.timeline-toggle-btn {
  display: flex;
  align-items: center;
  gap: 6px;
}

.diary :deep(.ant-picker-calendar) {
  border: none;
  flex: 1;
}

.dateCellRender {
  width: 95%;
  padding: 4px;
  border: 2px solid transparent;
  border-top: 2px solid #eee;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  aspect-ratio: 1 / 1;
  /* 确保高度与宽度一致 */
  margin-bottom: 5%;
}

.date-content {
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.hasTask {
  background: #ededed;
  color: #266fe8;
  border-radius: 4px;
}

.activeDate>.date-content.hasTask {
  background: transparent;
}

.activeDate {
  border: 2px solid #266fe8;
  border-radius: 4px;
}

.task-content {
  height: calc(100vh - 250px);
  min-height: 400px;
  width: 100%;
  overflow: hidden;
}

.task-footer {
  text-align: right;
}

.task-footer button {
  margin-left: 10px;
}

.icon-editor {
  position: absolute;
  right: 4px;
  bottom: 4px;
  color: #266fe8;
  display: none;
  font-size: 16px;
}

.activeDate .icon-editor {
  display: block;
}

.timeline-drawer {
  height: calc(100% - 20px);
  overflow-y: auto;
}

.timeline-search {
  margin-bottom: 16px;
}

.timeline-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  position: relative;
  padding: 8px 32px 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.timeline-main {
  flex: 1;
  cursor: pointer;
  padding: 4px;
}

.timeline-main:hover {
  background-color: #f5f5f5;
}

.timeline-date {
  font-weight: bold;
  color: #266fe8;
}

.timeline-content {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.timeline-actions {
  position: absolute;
  top: 50%;
  right: 8px;
  transform: translateY(-50%);
  display: none;
  z-index: 2;
}

.timeline-item:hover .timeline-actions {
  display: block;
}

.delete-btn {
  color: #ff4d4f;
  padding: 4px;
  font-size: 14px;
  background-color: #fff;
  border-radius: 4px;
  opacity: 0.8;
  transition: all 0.3s;
}

.delete-btn:hover {
  color: #ff7875;
  background-color: #fff;
  opacity: 1;
  transform: scale(1.1);
}

:deep(.ant-timeline-item-content) {
  top: -6px;
}

:deep(.ant-picker-calendar) {
  overflow-y: auto;
}

.custom-close-btn {
  color: #000;
  font-size: 16px;
  padding: 0;
  height: auto;
  width: auto;
  min-width: auto;
}

.custom-close-btn:hover {
  color: #266fe8;
  background-color: transparent;
}

.timeline-group {
  margin-bottom: 24px;
}

.timeline-group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f0f5ff;
  border-left: 4px solid #266fe8;
  border-radius: 0 4px 4px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
}

.timeline-group-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding: 12px 16px;
  flex: 1;
}

.timeline-group-actions {
  padding: 12px 16px;
  margin-bottom: 0;
  margin-right: 0;
}

.batch-delete-btn {
  color: #ff4d4f;
  padding: 4px;
  font-size: 14px;
  background-color: rgb(240, 245, 255);
  border-radius: 4px;
  opacity: 0.8;
  transition: all 0.3s;
}

.batch-delete-btn:hover {
  color: #ff7875;
  background-color: rgb(240, 245, 255);
  opacity: 1;
  transform: scale(1.1);
}
</style>